#!/usr/bin/env bash

# Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

srcdir=robot_middleware

cd ${srcdir} || exit 1
sed -i 's#path = "../dora#path = "../dora-0.3.12#g' Cargo.toml || exit 1
sed -i -E 's#ipc_rust = \{ path = "(.*)" \}#ipc_rust = \{ path = "../communication_ipc/interfaces/innerkits/rust" \}#' Cargo.toml || exit 1
cargo fetch || exit 1

if [ "${triple_env}" == "ohos" ]; then
    # fix nix<0.29
    # FIXME: better way to do this?
    for i in /.cargo/registry/src/*/nix-*/src/; do
        has_ohos=$(cat $i/sys/statfs.rs | grep "target_env = \"ohos\"")
        if [ $? -ne 0 ]; then
            nix_version=${i##}
            find $i -name '*.rs' -exec sed -i 's/target_env = \"musl\"/target_env = \"ohos\"/g' {} \;
        fi

        # mqueue and aio are not supported in ohos 4.1
        sed -i 's/pub mod mqueue;/\/\/pub mod mqueue;/g' $i/lib.rs
        sed -i 's/pub mod aio;/\/\/pub mod aio;/g' $i/sys/mod.rs
    done

    # FIXME ohos time_service_ndk is not supported in ohos 4.1, so let time zone be wrong
    for i in /.cargo/registry/src/*/iana-time-zone-*/src/; do
        sed -i 's/tz_ohos.rs/tz_linux.rs/g' $i/lib.rs
    done
fi

cargo_extra_args=()
if [ "${arch}" != "${host_arch}" ]; then
    cargo_extra_args+=(--target ${triple_normalized}) # cross-compiling
fi

cargo build \
    --release \
    --features no-sa \
    -j ${MAX_JOBS} \
    ${cargo_extra_args[@]} \
    || exit 1

extra_args=()
if [ "${arch}" != "${host_arch}" ]; then
    extra_args+=(-DCMAKE_SYSTEM_NAME=Linux) # cross-compiling
    extra_args+=(-DCMAKE_SYSTEM_PROCESSOR=${arch})
    extra_args+=(-DCODEGEN_PATH=/host/usr/bin/ohmw-codegen)
fi

cd .. || exit 1
mkdir -p build/generated
cmake \
    -S ${srcdir} \
    -B build \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=/usr \
    -DWITH_DORA=OFF \
    ${extra_args[@]} \
    || exit 1
make -C build -j ${MAX_JOBS} || exit 1
